package org.esprit.ocm.server.metier.ec2.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.esprit.ocm.client.rpc.ec2.RegionService;
import org.esprit.ocm.dto.impl.AwsCredentialsDto;
import org.esprit.ocm.dto.impl.ServerDto;
import org.esprit.ocm.model.ec2.RegionMapping;

import com.xerox.amazonws.ec2.Jec2;
import com.xerox.amazonws.ec2.RegionInfo;

public class RegionServiceImpl extends BaseServiceImpl implements RegionService {
	
	/**
	 * List the AWS Regions.
	 * 
	 * @return
	 */
	public List<RegionMapping> listRegions(ServerDto server, AwsCredentialsDto credentials) {

		// initialize the interface
		 Jec2 ec2 = this.initConnection( server,  credentials);

		List<RegionMapping> result = new ArrayList<RegionMapping>();

		try {

			List<RegionInfo> regionInfos = ec2.describeRegions(new ArrayList<String>());
			
			for (RegionInfo from : regionInfos) {
				
				RegionMapping to = new RegionMapping();
				
				to.setName(from.getName());
				to.setUrl(from.getUrl());
				
				result.add(to);
			}

			return result;

		} catch (Exception ex) {
			Logger logger = Logger.getLogger(this.getClass().getName());
			logger.log(Level.SEVERE, "Listing regions failed: " + ex.getMessage());

			// ex.printStackTrace();

			return null;
		}

	}
}